package com.cj.common.utils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.*;
import com.cj.common.constant.Constant;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @Author cheng jun
 * @Description:
 * @Date 2021/8/21 15:46
 */
@Slf4j
@Data
public class ExcelsUtil {

    /**
     * 姓名
     */
    private String name;

    /**
     * 年龄
     */
    private int age;

    /**
     * 分数
     */
    private int score;

    /**
     * 时间
     */
    private Date time;

    public ExcelsUtil(String name, int age, int score, Date time) {
        this.name = name;
        this.age = age;
        this.score = score;
        this.time = time;
    }

    /**
     * 导出到前端下载
     * @param request
     * @param response
     */
    public static void excelExport(HttpServletRequest request, HttpServletResponse response, List<?> data, String fileType, String fileName) {
        ExcelWriter writer;
        // 数据量大的用大数据导出
        if (data != null && data.size() > Constant.EXCEL_THRESHOLD) {
            writer=  ExcelUtil.getBigWriter();
        } else {
            writer = ExcelUtil.getWriter();
        }

        ServletOutputStream out = null;
        try {
            // 自定义标题别名
            writer.addHeaderAlias("name", "姓名");
            writer.addHeaderAlias("age", "年龄");
            writer.addHeaderAlias("score", "分数");
            writer.addHeaderAlias("time", "时间");

            // 定义单元格背景色
            StyleSet style = writer.getStyleSet();
            // 第二个参数表示是否也设置头部单元格背景
            style.setBackgroundColor(IndexedColors.WHITE, false);
            // todo(excel日期格式化)

            // 设置内容字体
            Font font = writer.createFont();
            font.setBold(true);
            font.setColor(Font.COLOR_RED);
            font.setItalic(true);
            // 第二个参数表示是否忽略头部样式
            writer.getStyleSet().setFont(font, true);

            // 一次性写出内容，使用默认样式，强制输出标题
            writer.write(data, true);

            // excel类型(xls和xlsx)
            if (Objects.equals(Constant.EXCEL_SUFFIX_XLS, fileType)) {
                response.setContentType("application/vnd.ms-excel");
            } else if (Objects.equals(Constant.EXCEL_SUFFIX_XLSX, fileType)) {
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            }

            // 解决文件名中文乱码
            String codedFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            // 浏览器名称
            String agent = request.getHeader("USER-AGENT").toLowerCase();
            if (agent.contains("firefox")) {
                response.setCharacterEncoding("utf-8");
                response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes(), "ISO8859-1") + fileType);
            } else {
                response.setHeader("content-disposition", "attachment;filename=" + codedFileName + fileType);
            }

            // out为OutputStream，需要写出到的目标流
            out=response.getOutputStream();

            writer.flush(out, true);
        } catch (IOException e) {
        } finally {
            // 关闭writer，释放内存
            writer.close();
            // 此处记得关闭输出Servlet流
            IoUtil.close(out);
        }
    }

    /**
     * 本地下载
     * @param data
     * @param fileType
     * @param fileName
     * @param path
     */
    public static void excelExport(List<?> data, String fileType, String fileName, String path) {
        // 自动关闭writer，释放内存
        try (BigExcelWriter writer = ExcelUtil.getBigWriter(path + fileName + fileType)) {
            // 一次性写出内容，使用默认样式
            writer.write(data);
        }
    }

    /**
     * 前端导入
     * @param file
     */
    public static void excelRead(MultipartFile file) {
        // todo(拦截器走了两遍,第二遍触发了网关验证)
        try (ExcelReader reader = ExcelUtil.getReader(file.getInputStream())){
            List<Map<String,Object>> list = reader.readAll();
            System.out.println(list);
        } catch (IOException e) {
        }
    }

    public static List<ExcelsUtil> getData() {
        List<ExcelsUtil> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add(new ExcelsUtil("张三" + i, 2 + i, 10 + i, new Date()));
        }

        return list;
    }


    public static void main(String[] args) {
        List<ExcelsUtil> list = ExcelsUtil.getData();
        for (int i = 1; i < list.get(0).getClass().getDeclaredFields().length; i++) {
            System.out.println(list.get(0).getClass().getDeclaredFields()[i].getName());
        }
    }
}
